package com.dzz.base.shiro;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName ShiroConfig
 * @author KRIC
 * @Date: 2018/9/19 14:39
 * @Description:
 */
@Configuration
public class ShiroConfig {
    /**
     * 自定义的Realm
     */
    @Bean(name = "myShiroRealm")
    public MyShiroRealm myShiroRealm() {
        return new MyShiroRealm();
    }

    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//        设置realm.
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }

    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        //1.定义shiroFactoryBean
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //2.设置securityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //3.LinkedHashMap是有序的，进行顺序拦截器配置
        Map<String, String> filterChainMap = new LinkedHashMap<String, String>();
//        无须拦截
        filterChainMap.put("/user/**","anon");
        filterChainMap.put("/css/**","anon");
        filterChainMap.put("/imgs/**","anon");
        filterChainMap.put("/js/**","anon");
        filterChainMap.put("/vendor/**","anon");
        //4.配置logout过滤器
        filterChainMap.put("/user/logout", "logout");
        //5.所有url必须通过认证才可以访问
//        todo 测试用
//        filterChainMap.put("/**", "anon");
        filterChainMap.put("/**", "authc");
        //6.设置默认登录的url
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        //7.设置成功之后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index.html");
        //8.设置未授权界面
        shiroFilterFactoryBean.setUnauthorizedUrl("/login.html");
        //9.设置shiroFilterFactoryBean的FilterChainDefinitionMap
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap);
        return shiroFilterFactoryBean;
    }
}
